package com.example.demo.service;

import com.example.demo.mapper.ArtMapper;
import com.example.demo.model.dto.art.ArtListDto;
import com.example.demo.model.dto.art.ArticlePubDto;
import com.example.demo.model.entity.ArtPhoto;
import com.example.demo.model.entity.Artinfo;
import com.example.demo.model.entity.Likes;
import com.example.demo.model.vo.ArtinfoVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User:龙宝
 * Date:2024-05-14
 * Time:9:04
 */
@Service
public class ArtService {
    @Autowired
    private ArtMapper artMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;

    //发布作品
    public int pub(ArticlePubDto dto, int userId){
        Artinfo artinfo = new Artinfo(dto, userId);
        ArtPhoto artPhoto = new ArtPhoto();
        //存art信息
        int resId = artMapper.pubArt(artinfo);
        if(resId <= 0 || artinfo.getId() <= 0){
            return -1;
        }
        //存照片
        List<MultipartFile> photo = dto.getPhotos();
        for (int i = 0;i<photo.size();i++) {
            MultipartFile path = photo.get(i);
            artPhoto.setId(artinfo.getId());
            artPhoto.setPhoto_path(String.valueOf(path));
            artPhoto.setSort(i+1);
            int res = artMapper.pubArtPic(artPhoto);
            if(res <= 0){
                return -1;
            }
        }
        return 1;
    }

    //作品详情
    public ArtinfoVO artInfo(Integer id){

        Artinfo artinfo = artMapper.artInfo(id);
        List<ArtPhoto> artPhoto = artMapper.artInfoPhoto(id);
        if(artinfo == null || artPhoto.size() <= 0){
            return new ArtinfoVO();
        }
        ArtinfoVO artinfoVO = new ArtinfoVO(artinfo, artPhoto);
        return artinfoVO;
    }
    //查询作品列表
    public Map<Integer, List<ArtinfoVO>> list(ArtListDto dto, Integer loginUserId){
        List<ArtinfoVO> res;
        Map<Integer, List<ArtinfoVO>> map = new HashMap<>();
        // 1、查询artinfo
        switch (dto.getType()){
            case 1 -> {
                //查询全部
                res = artMapper.artList(dto);
            }
            case 2 -> {
                //个人列表
                if(dto.getUserId() == null || dto.getUserId() == 0) {
                    map.put(-1, null);
                    return map;
                }
                res = artMapper.artOneList(dto);
            }

            case 3 -> {
                //收藏列表
                if(dto.getUserId() == null || dto.getUserId() == 0) {
                    map.put(-1, null);
                    return map;
                }
                // 先通过收藏表，查询出有哪些，再查询作品详细信息
                List<Integer> artIds = artMapper.artCollectIdList(dto);
                if(artIds.isEmpty()){
                    map.put(0, null);
                    return map;
                }
                res  = artMapper.artById(artIds);
            }

            case 4 -> {
                //点赞列表
                if(dto.getUserId() == null || dto.getUserId() == 0) {
                    map.put(-1, null);
                    return map;
                }
                // 先通过点赞表，查询出有哪些，再查询作品详细信息
                List<Integer> likeIds = artMapper.artLikeIdList(dto);
                if(likeIds.isEmpty()){
                    map.put(0, null);
                    return map;
                }
                res = artMapper.artById(likeIds);
            }

            case 5 -> {
                //私密列表
                if(dto.getUserId() == null || dto.getUserId() == 0) {
                    map.put(-1, null);
                    return map;
                }
                if(dto.getUserId() != loginUserId){
                    map.put(-1, null);
                    return map;
                }
                res = artMapper.artSpecialList(dto.getUserId(), 2);
            }

            case 6 -> {
                //草稿列表
                if(dto.getUserId() == null || dto.getUserId() == 0) {
                    map.put(-1, null);
                    return map;
                }
                if(dto.getUserId() != loginUserId){
                    map.put(-1, null);
                    return map;
                }
                res = artMapper.artSpecialList(dto.getUserId(), 3);
            }

            default -> {
                map.put(-1, null);
                return map;
            }
        }
        // 2、查询photos
        for(int i = 0;i<res.size();i++){
            List<ArtPhoto> photos = new ArrayList<>();
            photos = artMapper.artPhotoById(res.get(i).getId());
            res.get(i).setPhotos(photos);
        }
        map.put(1, res);
        return map;
    }

    //删除作品
    public Integer del(Integer userId, Integer artId){
        //查询artId的作者是不是userId
        Integer userIdByArt = artMapper.userIdByArt(artId);
        if(userId != userIdByArt){
            return 1003;
        }
        //删除操作
        Integer resId = artMapper.delArt(artId);
        if(resId != 1){
            return 1004;
        }
        artMapper.delArtPhotos(artId);
        return 1;
    }
    //点赞作品
    public Integer like(Integer userId, Integer artId){
        //查询该文章 - 检查其是否具备点赞条件（草稿、私密作品点赞失败）
        Artinfo artinfo = artMapper.artInfo(artId);
        if(artinfo == null || artinfo.getStat() != 1){
            return 0;
        }
        //当前userid是否对art已经点赞了
        Likes reslike = artMapper.artIsLike(userId, artId);

        if(reslike == null){
            //第一次点赞-新增
            Likes likes = new Likes(userId, artinfo.getUserId(),artId);
            artMapper.artLike(likes);
            return 1;
        }
        //点赞
        if(reslike.getStat() == 0){
            artMapper.alterArtLike(reslike.getId(), 1);
            return 1;
        } else{
            //取消点赞
            artMapper.alterArtLike(reslike.getId(), 0);
            return -1;
        }
    }

    //收藏作品
    public Integer collect(Integer userId, Integer artId){
        //查询该文章 - 检查其是否具备点赞条件（草稿、私密作品点赞失败）
        Artinfo artinfo = artMapper.artInfo(artId);
        if(artinfo == null || artinfo.getStat() != 1){
            return 0;
        }
        //当前userid是否对art已经点赞了
        Likes reslike = artMapper.artIsCollect(userId, artId);

        if(reslike == null){
            //第一次点赞-新增
            Likes likes = new Likes(userId, artinfo.getUserId(),artId);
            artMapper.artCollect(likes);
            return 1;
        }
        //点赞
        if(reslike.getStat() == 0){
            artMapper.alterArtCollect(reslike.getId(), 1);
            return 1;
        } else{
            //取消点赞
            artMapper.alterArtCollect(reslike.getId(), 0);
            return -1;
        }
    }

    // 作品的三连数据
    public HashMap<String, Object> artStat(Integer id){
        HashMap<String, Object> map = new HashMap<>();
        boolean res = redisTemplate.opsForHash().hasKey("stat" + id, "likeCnt");
        System.out.println(res);
        if(res){
            Object likeCnt = redisTemplate.opsForHash().get("stat" + String.valueOf(id), "likeCnt");
            Object collectCnt = redisTemplate.opsForHash().get("stat" + String.valueOf(id), "collectCnt");
            Object commentCnt = redisTemplate.opsForHash().get("stat" + String.valueOf(id), "commentCnt");
            map.put("likeCnt", likeCnt);
            map.put("collectCnt", collectCnt);
            map.put("commentCnt", commentCnt);
            return map;
        }
        //redis中暂无数据， 要从数据库中获取
        Integer likeCnt = artMapper.likeArtCnt(id);
        Integer collectCnt = artMapper.collectArtCnt(id);
        Integer commentCnt = artMapper.commentArtCnt(id);
        map.put("likeCnt", likeCnt);
        map.put("collectCnt", collectCnt);
        map.put("commentCnt", commentCnt);
        Thread t = new Thread(){
            @Override
            public void run() {
                redisTemplate.opsForHash().put("stat" + id,"likeCnt", likeCnt.toString());
                redisTemplate.opsForHash().put("stat" + id,"collectCnt", collectCnt.toString());
                redisTemplate.opsForHash().put("stat" + id, "commentCnt", commentCnt.toString());
            }
        };
        t.start();
        return map;
    }
}
